<?php
// $Id$

/**
 * Controller_My 控制器
 */
class Controller_My extends Controller_Abstract
{
	private $userinfo = array();
	private $current_url;
	function __construct($app){
		parent::__construct($app);
		//购物车中的数量
		$shoppingcartCount = 0;
		//登录用户信息
		$user = $this->_app->currentUser();
		if(!empty($user)){
			if($user['user_type'] == 3){
				if(User::find('userid=?',$user['id'])->getCount()){
					$this->userinfo = User::find('userid=?',$user['id'])->getOne();
					//dump($this->userinfo);
					$shoppingcartCount = Shoppingcart::find("user_id = '".$this->userinfo['userid']."'")->getCount();
				}
			}
		}
		$this->_view['shoppingcartCount'] = $shoppingcartCount;
		$this->_view['user'] = $user;
		//所有栏目的信息
		$array_cat = array();
		$allCatData =  Newstype::find('isdelete = 0')->getAll()->toArray();
		foreach($allCatData as $k => $v){
			switch($v['type_flag']){
				case '1':
					$href = url('index/news',array('catId'=>$v['id']));
				break;
				case '2':
					$href = url('index/cate',array('catId'=>$v['id']));
				break;
				case '3':
					$href = 'javascript:void(0);';
				break;
			}
			if(!empty($v['the_url'])){
				$href = $v['the_url'];
			}
			$array_cat[$v['id']]['href'] = $href;
			$array_cat[$v['id']]['type_name'] = $v['type_name'];	
		}
		$this->_view['array_cat'] = $array_cat;
		$this->_view['rootid'] = 0;
	}
	function actionIndex()
	{
		//登录判断
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user = $this->userinfo;
		//温馨提示
		$countMsg = array();
		$countMsg['order1'] = Orders::find("user_id='".$user['id']."' and order_flag = 1")->getCount();//未支付订单
		$countMsg['order2'] = Orders::find("user_id='".$user['id']."' and order_flag = 2")->getCount();//已支付订单
		$countMsg['favor'] = Favor::find("uid='".$user['id']."'")->getCount();//我的收藏
		$countMsg['shoppingcart'] = Shoppingcart::find("user_id='".$user['id']."'")->getCount();//我的购物车
		$this->_view['countMsg'] = $countMsg;	
		//我的课程
		$courseuser = Courseuser::find('user_id=?', $user['id'])->getAll();
		$this->_view['courseuser'] = $courseuser;
		//左栏
	}
	//登录
	function actionLogin(){
		$msg = '';
		if(isset($_REQUEST['message'])){
			$message = addslashes(trim($_REQUEST['message']));
			$msg_arr = Q::ini('appini/message');
			if(array_key_exists($message,$msg_arr)){
				$msg = $msg_arr[$message];
			}
		}

		 $form = new Form_UserLogin(url('admin/login'));
        $error = array(
        			'username' 	=> '',
        			'password' 	=> '',
        			'message'	=> '',
        			);
        $user_type = 3;
        if ($this->_context->isPOST() && $form->validate($_POST))
        {//dump($_POST);
            try
            {
                // 使用 acluser 插件的 validateLogin() 方法验证登录并取得有效的 user 对象
		        $user = User::meta()->validateLogin($form['username']->value, $form['password']->value);                
		        if(0 && !$user->validCheck()){
					$error['username'] = "对不起，该学生账号已经过期！";
					$msg = $error['username'];
		        }else{
		            // 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
		            $aclData = $user->aclData();
					$aclData['id'] = $user->id;
		            //$aclData['school_id'] = $user['school_id'];
		            //print_r($aclData);
		            $this->_app->changeCurrentUser($aclData, 'MEMBER');
					// 登录成功后，重定向浏览器
					$jump_url = url('users');
					if(isset($_COOKIE['mynep_jump_url'])){
						$mynep_jump_url = $_COOKIE['mynep_jump_url'];
						if($mynep_jump_url){
							$jump_url = 'http://'.$mynep_jump_url;
						}
					}
                    return $this->_redirect($jump_url);
                    //return $this->_redirect($this->actionCjgate());
		        } 
                
            }
            catch (AclUser_UsernameNotFoundException $ex)
            {
				$error['message'] = "您输入的登录帐号 {$form['username']->value} 不存在";
				$msg = $error['message'];
			}
            catch (AclUser_WrongPasswordException $ex)
            {
				$error['password'] = "您输入的密码不正确";
				$msg = $error['password'];
            }
        }
		//$this->_view['error'] = $error;
        //$this->_view['form'] = $form;

		$this->_view['msg'] = $msg;
	}
	/**
     * 注销
    */
    function actionLogout()
    {
       	$user = $this->_app->currentUser();
		$logout_url = url('index');
		$this->_app->cleanCurrentUser();
		setcookie('mynep_jump_url','',time()-3600,'/');
        return $this->_redirect($logout_url);
	}	
	//修改个人信息
	function actionMyinfo(){
		//未登录，跳转到登录页面
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}	
		//dump($this->userinfo);
			$message_success = '';
		if ($this->_context->isPOST() && isset($_POST['name'])){
			//if($imgcode == $_SESSION['askCode']){	
				$name = addslashes(trim($_REQUEST['name']));
				$gender = $_REQUEST['gender'];
				$mobile = addslashes(trim($_REQUEST['mobile']));
				$sql = "UPDATE core_user set name='".$name."',gender='".$gender."',mobile='".$mobile."' where id = '".$this->userinfo['id']."'";
				$db = QDB::getConn();
				$db->execute($sql);
				$this->userinfo = User::find('id='.$this->userinfo['id'])->getOne()->toArray();
				$message_success = "信息修改成功！";
			//}else{
			//	$error_imgcode = '对不起，您的验证码输入不正确！';
			//}
		}	
		$this->_view['message_success'] = $message_success;
		$this->_view['userinfo'] = $this->userinfo;
		//左栏
	}
	//购物车
	function actionShoppingcart(){
		//echo $_COOKIE['mynep_jump_url'];		//未登录，跳转到登录页面
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		if(isset($_GET['course_id'])){
			$course_id = intval($_GET['course_id']);
			if($course_id){
				//判断该课程是否已经在订单中存在或者在学生课程关联表中存在
				$orderCount = Ordercourse::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
				$courseuserCount = Courseuser::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
				if($orderCount || $courseuserCount){
				}else{
					$date_add = time();
					$count = Shoppingcart::find("course_id='$course_id' and user_id='$user_id'")->getCount();
					if($count == 0){
						$data_insert = array(
										'course_id'	=> $course_id,
										'user_id'	=> $user_id,
										'date_add'	=> $date_add,
										);
						$shoppingcart = new Shoppingcart($data_insert);
						$shoppingcart->save();	
					}elseif($count == 1){
						$shoppingcart = Shoppingcart::find("course_id='$course_id' and user_id='$user_id'")->getOne();
						$data_update = array(
										'date_add'	=> $date_add,
										);
						$shoppingcart -> changeProps($data_update);
						$shoppingcart -> save();
					}
				}
			}
		}
		//购物车数据
		$myData = Shoppingcart::find("user_id = '$user_id'")->order("date_add desc")->getAll();
		$this->_view['myData'] = $myData;
	}
	//删除购物车
	function actionDeletecart(){
		$flag = 0;
		if(isset($_POST['cart_id'])){
			$cart_id = intval(trim($_POST['cart_id']));
			if($cart_id){
				Shoppingcart::meta()->destroyWhere("cart_id=?",$cart_id);
				$flag = 1;	
			}
		}
		echo $flag;
		exit();	
	}
	//清空购物车
	function actionClearcart(){
		$flag = 0;
		if(!empty($this->userinfo)){
			Shoppingcart::meta()->destroyWhere("user_id=?",$this->userinfo['id']);
			$flag = 1;	
		}
		echo $flag;
		exit();	
	}
	//修改密码
	function actionMypassword(){
		//未登录，跳转到登录页面
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$message_success = '';
		if ($this->_context->isPOST() && isset($_POST['pass'])){
			//if($imgcode == $_SESSION['askCode']){	
				$pass = trim($_REQUEST['pass']);
				$pass_md5 = md5($pass);
				$sql = "UPDATE core_user set pass='".$pass_md5."' where id = '".$this->userinfo['id']."'";
				$db = QDB::getConn();
				$db->execute($sql);
				$message_success = "密码修改成功！";
			//}else{
			//	$error_imgcode = '对不起，您的验证码输入不正确！';
			//}
		}	
		$this->_view['message_success'] = $message_success;

	}
	//验证原密码是否正确
	function actionPassistrue(){
		$pass_old = addslashes(trim($_REQUEST['pass_old']));
		$pass_old_md5 = md5($pass_old);
		$msg = 1;
		if($pass_old_md5 == $this->userinfo['pass']){
			$msg = 0;	
		}
		//$msg = $pass_old_md5;	
		echo $msg;
		exit();
	}
	//确认支付页面
	function actionConfirmpayment(){
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		$order_id = 0;
		$orderData = array();
		if(isset($_GET['where_from'])){
			$where_from = trim($_GET['where_from']);
			$date_str = date('Ymd');
			$date_add = time();
			if($where_from == 'course'){
				$course_id = intval($_GET['course_id']);
				if($course_id){
					//判断该课程是否已经在订单中存在或者在学生课程关联表中存在
					$orderCount = Ordercourse::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
					$courseuserCount = Courseuser::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
					if($orderCount || $courseuserCount){
						//return $this->_redirect( url('users/orderlist'));
						$this->_view['message'] = "对不起，该课程您已经购买过了或者已经生成订单！";
						$this->_viewname = 'jump';
						//exit();
					}else{
						$today_count = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->getCount();
						if($today_count == 0){
							$num = 1;
							$order_number = $date_str.'_'.$user_id.'_'.$num;
						}else{
							$top_order = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->order('num desc')->getOne()->toArray();
							$num = $top_order['num']+1;
							$order_number = $date_str.'_'.$user_id.'_'.$num;
						}		
						$data_insert_orders = array(
								'user_id'	=> $user_id,
								'order_number'	=> $order_number,
								'date_add'	=> $date_add,
								'date_str'	=> $date_str,
								'num'		=> $num,
							);
						$obj_order = new Orders($data_insert_orders);
						$order_id = $obj_order->save()->order_id;
						$data_insert_ordercourse = array(
								'order_id'	=> $order_id,
								'course_id'	=> $course_id,
								'user_id'	=> $user_id,
							);
						$obj_ordercourse = new Ordercourse($data_insert_ordercourse);
						$obj_ordercourse->save();
					}
				}
			}elseif($where_from == 'shoppingcart'){
				$shoppingcartCount = Shoppingcart::find("user_id = '".$user_id."'")->getCount();
				if($shoppingcartCount){
					$today_count = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->getCount();
					if($today_count == 0){
						$num = 1;
						$order_number = $date_str.'_'.$user_id.'_'.$num;
					}else{
						$top_order = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->order('num desc')->getOne()->toArray();
						$num = $top_order['num']+1;
						$order_number = $date_str.'_'.$user_id.'_'.$num;
					}
					$data_insert_orders = array(
							'user_id'	=> $user_id,
							'order_number'	=> $order_number,
							'date_add'	=> $date_add,
							'date_str'	=> $date_str,
							'num'		=> $num,
						);
					$obj_order = new Orders($data_insert_orders);
					$order_id = $obj_order->save()->order_id;
					$arr_shoppingcart = Shoppingcart::find("user_id = '".$user_id."'")->getAll()->toArray();
					foreach($arr_shoppingcart as $k=>$v){
						$data_insert_ordercourse = array(
							'order_id'	=> $order_id,
							'course_id'	=> $v['course_id'],
							'user_id'	=> $user_id,
						);
						$obj_ordercourse = new Ordercourse($data_insert_ordercourse);
						$obj_ordercourse->save();
					}
					Shoppingcart::meta()->destroyWhere("user_id=?",$user_id);
				}else{
					return $this->_redirect( url('users/orderlist'));
				}	
			}
		}
		if(isset($_GET['order_id'])){
			$order_id = intval(trim($_GET['order_id']));
		}
		if($order_id){
			$orderData = Orders::find("order_id = '".$order_id."'")->getOne();
			
		}
		$myData = Ordercourse::find("order_id = '".$order_id."'")->getAll();
		$this->_view['orderData'] = $orderData;
		$this->_view['myData'] = $myData;
	}
	//订单详细页面
	function actionOrderdetail(){
		//未登录，跳转到登录页面
		//$current_url = Helper_Util::str_current_url();
		//echo $current_url.'<br />';
		//echo $_SERVER['SERVER_NAME'];
		//setcookie('mynep_jump_url',$current_url,time()+3600,'/','localhost',1);
		//echo isset($_COOKIE['cookietest']).'<br />';
		//echo $_COOKIE['mynep_jump_url'];
		//QSession_Provider_Cookie::write('myurl',$current_url);
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		$order_id = 0;
		$orderData = array();
		if(isset($_GET['where_from'])){
			$where_from = trim($_GET['where_from']);
			$date_str = date('Ymd');
			$date_add = time();
			if($where_from == 'course'){
				$course_id = intval($_GET['course_id']);
				if($course_id){
					//判断该课程是否已经在订单中存在或者在学生课程关联表中存在
					$orderCount = Ordercourse::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
					$courseuserCount = Courseuser::find("user_id = '".$user_id."' and course_id = '".$course_id."'")->getCount();
					if($orderCount || $courseuserCount){
						//return $this->_redirect( url('users/orderlist'));
						$this->_view['message'] = "对不起，该课程您已经购买过了或者已经生成订单！";
						$this->_viewname = 'jump';
						//exit();
					}else{
						$today_count = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->getCount();
						if($today_count == 0){
							$num = 1;
							$order_number = $date_str.'_'.$user_id.'_'.$num;
						}else{
							$top_order = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->order('num desc')->getOne()->toArray();
							$num = $top_order['num']+1;
							$order_number = $date_str.'_'.$user_id.'_'.$num;
						}		
						$data_insert_orders = array(
								'user_id'	=> $user_id,
								'order_number'	=> $order_number,
								'date_add'	=> $date_add,
								'date_str'	=> $date_str,
								'num'		=> $num,
							);
						$obj_order = new Orders($data_insert_orders);
						$order_id = $obj_order->save()->order_id;
						$data_insert_ordercourse = array(
								'order_id'	=> $order_id,
								'course_id'	=> $course_id,
								'user_id'	=> $user_id,
							);
						$obj_ordercourse = new Ordercourse($data_insert_ordercourse);
						$obj_ordercourse->save();
					}
				}
			}elseif($where_from == 'shoppingcart'){
				$shoppingcartCount = Shoppingcart::find("user_id = '".$user_id."'")->getCount();
				if($shoppingcartCount){
					$today_count = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->getCount();
					if($today_count == 0){
						$num = 1;
						$order_number = $date_str.'_'.$user_id.'_'.$num;
					}else{
						$top_order = Orders::find("date_str = '".$date_str."' and user_id = '".$user_id."'")->order('num desc')->getOne()->toArray();
						$num = $top_order['num']+1;
						$order_number = $date_str.'_'.$user_id.'_'.$num;
					}
					$data_insert_orders = array(
							'user_id'	=> $user_id,
							'order_number'	=> $order_number,
							'date_add'	=> $date_add,
							'date_str'	=> $date_str,
							'num'		=> $num,
						);
					$obj_order = new Orders($data_insert_orders);
					$order_id = $obj_order->save()->order_id;
					$arr_shoppingcart = Shoppingcart::find("user_id = '".$user_id."'")->getAll()->toArray();
					foreach($arr_shoppingcart as $k=>$v){
						$data_insert_ordercourse = array(
							'order_id'	=> $order_id,
							'course_id'	=> $v['course_id'],
							'user_id'	=> $user_id,
						);
						$obj_ordercourse = new Ordercourse($data_insert_ordercourse);
						$obj_ordercourse->save();
					}
					Shoppingcart::meta()->destroyWhere("user_id=?",$user_id);
				}else{
					return $this->_redirect( url('users/orderlist'));
				}	
			}
		}
		if(isset($_GET['order_id'])){
			$order_id = intval(trim($_GET['order_id']));
		}
		if($order_id){
			$orderData = Orders::find("order_id = '".$order_id."'")->getOne();
			
		}
		$myData = Ordercourse::find("order_id = '".$order_id."'")->getAll();
		$this->_view['orderData'] = $orderData;
		$this->_view['myData'] = $myData;
	}
	function actionOrderlist(){
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		$search_where = " user_id = '".$user_id."'";
		$order_flag = 0;
		if(isset($_GET['order_flag'])){
			$order_flag = intval($_GET['order_flag']);
			$search_where .= " and order_flag = '".$order_flag."'";
		}	
		$page = (int)$this->_context->page;
		if ($page==0) $page++;
		$limit = $this->_context->limit ? $this->_context->limit : 15;
		
		$q = Orders::find($search_where)->order('date_add desc')->limitPage($page, $limit);
		$list = $q->getAll()->toArray();
		foreach($list as $k => $v){
			$list[$k]['ordercourse'] = Ordercourse::find("order_id='".$v['order_id']."'")->getAll();
		}
		$this->_view['pager'] = $q->getPagination();
		$this->_view['list'] = $list;
		$this->_view['start'] = ($page-1)*$limit;
		$this->_view['order_flag'] = $order_flag;
		switch($order_flag){
			case 0:
				//左栏
				$this->_view['on_menu'] = 7;
				break;
			case 1:
				//左栏
				$this->_view['on_menu'] = 8;
				break;
			case 2:
				//左栏
				$this->_view['on_menu'] = 9;
				break;
		}
	}
	function actionOrderpay(){
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		if(isset($_GET['order_id'])){
			$order_id = $_GET['order_id'];
			$orderCount = Orders::find("order_id = '".$order_id."' and user_id = '".$user_id."'")->getCount();
			if($orderCount){
				$sql = "UPDATE lms_order set order_flag='2' where order_id = '".$order_id."'";
				$db = QDB::getConn();
				$db->execute($sql);

				$allData = Ordercourse::find("order_id = '".$order_id."'")->getAll();
				$date_get = time();
				foreach($allData as $k => $v){
					$count = Courseuser::find("user_id = '".$user_id."' and course_id = '".$v->course_id."'")->getCount();
					if(!$count){
						$data_insert = array(
							'user_id' => $user_id,
							'course_id'	=> $v->course_id,
							'date_get'	=> $date_get,
						);
						$obj_courseuser = new Courseuser($data_insert);
						$obj_courseuser->save();
					}
				}
			}
		}
	}
	function actionOrdercancel(){
		if(empty($this->userinfo)){
			$current_url = Helper_Util::str_current_url();
			setcookie('mynep_jump_url',$current_url,time()+3600,'/');
			return $this->_redirect( url('admin/login',array('message'=>'1')));
		}
		$user_id = $this->userinfo['id'];
		if(isset($_GET['order_id'])){
			$order_id = $_GET['order_id'];
			$count = Orders::find("order_id = '".$order_id."' and user_id = '".$user_id."'")->getCount();
			if($count){
				Orders::meta()->destroyWhere("order_id =? and user_id=?",$order_id,$user_id);
				Ordercourse::meta()->destroyWhere("order_id=?",$order_id);
				return $this->_redirect( url('users/orderlist'));
			}
		}
	}
}

